const sqlExcutor = require('../../database/order/query')

const getPageList = async (req, res) => {
  // 获取请求数据
  const page = req.params.page || 1
  const pageSize = req.params.pageSize || 10
  const searchObj = req.query
  // 重新设置查询条件
  const newSearchObj = {}
  const rangeSearchObj = {}
  Object.keys(searchObj).forEach(key => {
    if (key === 'outTradeNo') {
      newSearchObj['out_trade_no'] = searchObj[key]
    } else if (key === 'orderStatus') {
      newSearchObj['order_status'] = searchObj[key]
    } else if (key === 'phone') {
      newSearchObj['phone'] = searchObj[key]
    } else if (key === 'createTimeBegin') {
      rangeSearchObj['createTimeBegin'] = searchObj[key]
    } else if (key === 'createTimeEnd') {
      rangeSearchObj['createTimeEnd'] = searchObj[key]
    }
  })

  let result = [], total = []
  if (Object.keys(newSearchObj).length > 0 || Object.keys(rangeSearchObj).length > 0) {
    // 条件查询
    const baseSql = `SELECT * FROM order_info WHERE 1=1`
    const searchSql = sqlExcutor.getSearchSql(newSearchObj)
    const rangeSql = sqlExcutor.getRangeSql(rangeSearchObj)
    // 拼接查询sql
    let sql = baseSql
    if (Object.keys(newSearchObj).length > 0)
      sql += searchSql
    if (Object.keys(rangeSearchObj).length > 0)
      sql += rangeSql

    console.log(sql)
    result = await sqlExcutor.sqlExcute(sql)
    total = [{total: result.length }]
  } else {
    // 分页查询
    const sql = `SELECT * FROM order_info LIMIT ${(page - 1) * pageSize}, ${pageSize}`
    const sqlTotal = 'select count(*) as total from order_info'
    result = await sqlExcutor.sqlExcute(sql)
    total = await sqlExcutor.sqlExcute(sqlTotal)
  }

  // 查询课程名称
  for (const item of result) {
    const sql = `SELECT * FROM order_detail WHERE order_id = ${item.id}`
    let resultCourse = await sqlExcutor.sqlExcute(sql)
    item['param'] = resultCourse[0]
  }

  res.send({
    code: 20000,
    data: {
      records: result,
      total: total[0].total,
    }
  })
}

module.exports = {
  getPageList,

}
